package com.easy.controller;

import com.easy.bean.Administrator;
import com.easy.bean.User;
import com.easy.service.IAdministratorService;
import com.easy.util.LayData;
import com.easy.util.Page;
import com.easy.util.SYS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("administrator")
public class AdministratorController {
    @Autowired
    IAdministratorService administratorService;

    @RequestMapping("list")
    @ResponseBody
    public LayData getAdministratorList(Page page, String text){
        List<Administrator> list=administratorService.selectAdministrator(page,text);
        int count=administratorService.AdministratorCount(text);
        return new LayData(count,list);
    }

    @RequestMapping("delete")
    @ResponseBody
    public int deleteAdministrator(int id){
        return administratorService.deleteAdministrator(id);
    }

    @RequestMapping("add")
    @ResponseBody
    public int addAdministrator(Administrator administrator){
        if(administrator.getPassword()!=null){
            administrator.setPassword(SYS.digest(administrator.getPassword()));
        }
        return administratorService.addAdministrator(administrator);
    }

    @RequestMapping("edit")
    @ResponseBody
    public int editAdministrator(HttpSession session,Administrator administrator){
        Administrator admin=(Administrator) session.getAttribute("SYSTEM_LOGIN_ADMIN");
        administrator.setId(admin.getId());
        if(administrator.getPassword()!=null){
            administrator.setPassword(SYS.digest(administrator.getPassword()));
        }
        return administratorService.editAdministrator(administrator);
    }

    @RequestMapping("get")
    @ResponseBody
    public Administrator getAdministrator(HttpSession session){
        Administrator administrator=(Administrator) session.getAttribute("SYSTEM_LOGIN_ADMIN");
        return administratorService.getAdministratorByAccount(administrator.getAccount());
    }

    @RequestMapping("logout")
    @ResponseBody
    public void logout(HttpSession session){
        if (session != null) {
            session.removeAttribute(SYS.SYSTEM_LOGIN_ADMIN);
        }
    }

    @RequestMapping("verifyPassword")
    @ResponseBody
    public boolean verifyPassword(HttpSession session,Administrator administrator){
        Administrator loginAdmin=(Administrator) session.getAttribute("SYSTEM_LOGIN_ADMIN");
        return SYS.checkPass(administrator.getPassword(),administratorService.getAdministratorByAccount(loginAdmin.getAccount()).getPassword());
    }


}
